/*
 * Copyright 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.dexafree.materialList.listeners;

import com.dexafree.materialList.view.Configuration;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.ListContainer;
import ohos.agp.components.VelocityDetector;
import ohos.agp.utils.Rect;
import ohos.miscservices.timeutility.Time;
import ohos.multimodalinput.event.TouchEvent;
import utils.LogUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * A {@link Component} that makes the list items in a {@link } dismissable.
 * {@link } is given special treatment because by default it handles touches for its list
 * items... i.e. it's in charge of drawing the pressed state (the list selector), handling list item
 * clicks, etc.
 * <p/>
 * <p>After creating the listener, the caller should also call {@link
 * #()}, passing in the scroll listener
 * returned by {@link #makeScrollListener()}. If a scroll listener is already assigned, the caller
 * should still pass scroll changes through to this listener. This will ensure that this {@link
 * SwipeDismissRecyclerViewTouchListener} is paused during list view scrolling.</p>
 * <p/>
 * <p>Example usage:</p>
 * <p/>
 * <pre>
 * SwipeDismissRecyclerViewTouchListener touchListener =
 *         new SwipeDismissRecyclerViewTouchListener(
 *                 listView,
 *                 new SwipeDismissRecyclerViewTouchListener.OnDismissCallback() {
 *                     public void onDismiss(ListView listView, int[] reverseSortedPositions) {
 *                         for (int position : reverseSortedPositions) {
 *                             adapter.remove(adapter.getItem(position));
 *                         }
 *                         adapter.notifyDataSetChanged();
 *                     }
 *                 });
 * listView.setOnTouchListener(touchListener);
 * listView.setOnScrollListener(touchListener.makeScrollListener());
 * </pre>
 * <p/>
 * <p>This class Requires API level 12 or later due to use of {@link }.</p>
 * <p/>
 * <p>For a generalized {@link Component} that makes any view dismissable.</p>
 */
public class SwipeDismissRecyclerViewTouchListener implements Component.TouchEventListener {
    // Cached ViewConfiguration and system-wide constant values
    private final int mSlop;
    private final int mMinFlingVelocity;
    private final int mMaxFlingVelocity;
    private final long mAnimationTime;

    // Fixed properties
    private final ListContainer mRecyclerView;
    private final DismissCallbacks mCallbacks;
    private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero

    // Transient properties
    private final List<PendingDismissData> mPendingDismisses = new ArrayList<>();
    private int mDismissAnimationRefCount = 0;
    private float mDownX;
    private float mDownY;
    private boolean mSwiping;
    private int mSwipingSlop;
    private VelocityDetector mVelocityTracker;
    private int mDownPosition;
    private Component mDownView;
    private boolean mPaused;

    /**
     * The callback interface used by {@link SwipeDismissRecyclerViewTouchListener} to inform its
     * client about a successful dismissal of one or more list item positions.
     */
    public interface DismissCallbacks {
        /**
         * Called to determine whether the given position can be dismissed.
         *
         * @param position position
         * @return boolean
         */
        boolean canDismiss(int position);

        /**
         * Called when the user has indicated they she would like to dismiss one or more list item
         * positions.
         *
         * @param recyclerView           The originating {@link ohos.agp.components.ListContainer}.
         * @param reverseSortedPositions An array of positions to dismiss, sorted in descending order for convenience.
         */
        void onDismiss(ListContainer recyclerView, int[] reverseSortedPositions);
    }

    /**
     * Constructs a new swipe-to-dismiss touch listener for the given list view.
     *
     * @param recyclerView The list view whose items should be dismissable.
     * @param callbacks    The callback to trigger when the user has indicated that she would like to dismiss one or
     *                     more list items.
     */
    public SwipeDismissRecyclerViewTouchListener(ListContainer recyclerView, DismissCallbacks callbacks) {
        mSlop = Configuration.getTouchSlop();
        mMinFlingVelocity = Configuration.getMinimumFlingVelocity() * 16;
        mMaxFlingVelocity = Configuration.getMaximumFlingVelocity();
        mAnimationTime = 200;
        mRecyclerView = recyclerView;
        mCallbacks = callbacks;
    }

    /**
     * Enables or disables (pauses or resumes) watching for swipe-to-dismiss gestures.
     *
     * @param enabled Whether or not to watch for gestures.
     */
    public void setEnabled(boolean enabled) {
        mPaused = !enabled;
    }

    /**
     * Returns an {@link } to be added to the {@link } using
     * {@link Component#}. If a scroll listener is
     * already assigned, the caller should still pass scroll changes through to this listener. This
     * will ensure that this {@link SwipeDismissRecyclerViewTouchListener} is paused during list
     * view scrolling.</p>
     *
     * @return ScrolledListener
     * @see SwipeDismissRecyclerViewTouchListener
     */
    public ListContainer.ScrolledListener makeScrollListener() {
        return new ListContainer.ScrolledListener() {
            @Override
            public void scrolledStageUpdate(Component component, int newStage) {
                setEnabled(newStage != Component.SCROLL_AUTO_STAGE);
            }

            @Override
            public void onContentScrolled(Component component, int i, int i1, int i2, int i3) {
            }
        };
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        if (mViewWidth < 2) {
            mViewWidth = mRecyclerView.getWidth();
        }

        switch (touchEvent.getAction()) {
            case TouchEvent.PRIMARY_POINT_DOWN: {
                if (mPaused) {
                    return false;
                }

                // Find the child view that was touched (perform a hit test)
                Rect rect;
                int childCount = mRecyclerView.getChildCount();
                int[] listViewCoords = mRecyclerView.getLocationOnScreen();
                int x = (int) touchEvent.getPointerScreenPosition(0).getX() - listViewCoords[0];
                int y = (int) touchEvent.getPointerScreenPosition(0).getY() - listViewCoords[1];
                Component child;
                for (int i = 0; i < childCount; i++) {
                    child = mRecyclerView.getComponentAt(i);
                    if (child == null) {
                        continue;
                    }
                    rect = child.getComponentPosition();
                    if (rect.contains(x, y, x, y)) {
                        mDownView = child;
                        break;
                    }
                }
                if (mDownView != null) {
                    mDownX = touchEvent.getPointerScreenPosition(0).getX();
                    mDownY = touchEvent.getPointerScreenPosition(0).getY();
                    mDownPosition = mRecyclerView.getIndexForComponent(mDownView);
                    if (mCallbacks.canDismiss(mDownPosition)) {
                        mVelocityTracker = VelocityDetector.obtainInstance();
                        mVelocityTracker.addEvent(touchEvent);
                    } else {
                        mDownView = null;
                    }
                }
                return true;
            }

            case TouchEvent.CANCEL: {
                if (mVelocityTracker == null) {
                    break;
                }
                if (mDownView != null && mSwiping) {
                    // cancel
                    mDownView.createAnimatorProperty()
                            .moveToX(0)
                            .alpha(1)
                            .setDuration(mAnimationTime)
                            .start();
                }
                mVelocityTracker.clear();
                mVelocityTracker = null;
                mDownX = 0;
                mDownY = 0;
                mDownView = null;
                mDownPosition = ListContainer.INVALID_INDEX;
                mSwiping = false;
                break;
            }

            case TouchEvent.PRIMARY_POINT_UP: {
                if (mVelocityTracker == null) {
                    break;
                }
                float deltaX = (float) (touchEvent.getPointerScreenPosition(0).getX() - (double)mDownX);
                mVelocityTracker.addEvent(touchEvent);
                mVelocityTracker.calculateCurrentVelocity(1000);
                float velocityX = mVelocityTracker.getHorizontalVelocity();
                float absVelocityX = Math.abs(velocityX);
                float absVelocityY = Math.abs(mVelocityTracker.getVerticalVelocity());
                boolean dismiss = false;
                boolean dismissRight = false;
                if (Math.abs(deltaX) > (float) mViewWidth / 2 && mSwiping) {
                    dismiss = true;
                    dismissRight = deltaX > 0;
                } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
                        && absVelocityY < absVelocityX && mSwiping) {
                    // dismiss only if flinging in the same direction as dragging
                    dismiss = (velocityX < 0) == (deltaX < 0);
                    dismissRight = mVelocityTracker.getHorizontalVelocity() > 0;
                }
                if (dismiss && mDownPosition != ListContainer.INVALID_INDEX) {
                    // dismiss
                    final Component downView = mDownView; // mDownView gets null'd before animation ends
                    final int downPosition = mDownPosition;
                    ++mDismissAnimationRefCount;
                    mDownView.createAnimatorProperty()
                            .moveToX(dismissRight ? mViewWidth : -mViewWidth)
                            .alpha(0)
                            .setLoopedCount(0)
                            .setDuration(mAnimationTime)
                            .setStateChangedListener(new Animator.StateChangedListener() {
                                @Override
                                public void onStart(Animator animator) {
                                    LogUtil.debug("cpf", "onStart");
                                }

                                @Override
                                public void onStop(Animator animator) {
                                }

                                @Override
                                public void onCancel(Animator animator) {
                                }

                                @Override
                                public void onEnd(Animator animator) {
                                    performDismiss(downView, downPosition);
                                }

                                @Override
                                public void onPause(Animator animator) {
                                }

                                @Override
                                public void onResume(Animator animator) {
                                }
                            })
                            .start();
                } else {
                    // cancel
                    mDownView.setTranslationX(0);
                    mDownView.setAlpha(255f);
                }
                mVelocityTracker.clear();
                mVelocityTracker = null;
                mDownX = 0;
                mDownY = 0;
                mDownView = null;
                mDownPosition = ListContainer.INVALID_INDEX;
                mSwiping = false;
                break;
            }

            case TouchEvent.POINT_MOVE: {
                if (mVelocityTracker == null || mPaused) {
                    break;
                }
                mVelocityTracker.addEvent(touchEvent);
                float deltaX = (float) (touchEvent.getPointerScreenPosition(0).getX() - (double)mDownX);
                float deltaY = (float) (touchEvent.getPointerScreenPosition(0).getY() - (double)mDownY);
                if (Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) {
                    mSwiping = true;
                    mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop);
                }

                if (mSwiping) {
                    mDownView.setTranslationX((float) (deltaX - (double)mSwipingSlop));
                    mDownView.setAlpha((float) Math.max(0f, Math.min(1f,
                            1f - 2f * Math.abs(deltaX) / (double)mViewWidth)));
                    return true;
                }
                return true;
            }
        }
        return false;
    }


    static class PendingDismissData implements Comparable<PendingDismissData> {
        public int position;
        public Component view;

        public PendingDismissData(int position, Component view) {
            this.position = position;
            this.view = view;
        }

        @Override
        public int compareTo(PendingDismissData other) {
            // Sort by descending position
            return other.position - position;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            PendingDismissData that = (PendingDismissData) o;
            return position == that.position &&
                    Objects.equals(view, that.view);
        }

        @Override
        public int hashCode() {
            return Objects.hash(position, view);
        }
    }

    /**
     * dismissCard
     *
     * @param downView 需要移除的card
     * @param position card的位置
     */
    public void dismissCard(final Component downView, final int position) {
        float viewWidth = downView.getEstimatedWidth();
        ++mDismissAnimationRefCount;
        downView.createAnimatorProperty()
                .moveToX(viewWidth)
                .alpha(0)
                .setDuration(400)
                .setStateChangedListener(new Animator.StateChangedListener() {
                    @Override
                    public void onStart(Animator animator) {
                    }

                    @Override
                    public void onStop(Animator animator) {
                    }

                    @Override
                    public void onCancel(Animator animator) {
                    }

                    @Override
                    public void onEnd(Animator animator) {
                        performDismiss(downView, position);
                    }

                    @Override
                    public void onPause(Animator animator) {
                    }

                    @Override
                    public void onResume(Animator animator) {
                    }
                }).start();
    }

    private void performDismiss(final Component dismissView, final int dismissPosition) {
        // Animate the dismissed list item to zero-height and fire the dismiss callback when
        // all dismissed list item animations have completed. This triggers layout on each animation
        // frame; in the future we may want to do something smarter and more performant.
        final ComponentContainer.LayoutConfig lp = dismissView.getLayoutConfig();
        final int originalHeight = dismissView.getHeight();
        AnimatorValue animator = new AnimatorValue();
        animator.setLoopedCount(0);
        animator.setDuration(mAnimationTime);
        animator.setStateChangedListener(new Animator.StateChangedListener() {
            @Override
            public void onStart(Animator animator) {
            }

            @Override
            public void onStop(Animator animator) {
            }

            @Override
            public void onCancel(Animator animator) {
            }

            @Override
            public void onEnd(Animator animator) {
                --mDismissAnimationRefCount;
                if (mDismissAnimationRefCount == 0) {
                    // No active animations, process all pending dismisses.
                    // Sort by descending position
                    Collections.sort(mPendingDismisses);
                    int[] dismissPositions = new int[mPendingDismisses.size()];
                    for (int i = mPendingDismisses.size() - 1; i >= 0; i--) {
                        dismissPositions[i] = mPendingDismisses.get(i).position;
                    }
                    mCallbacks.onDismiss(mRecyclerView, dismissPositions);

                    // Reset mDownPosition to avoid MotionEvent.ACTION_UP trying to start a dismiss
                    // animation withProvider a stale position
                    mDownPosition = ListContainer.INVALID_INDEX;
                    ComponentContainer.LayoutConfig lp;
                    for (PendingDismissData pendingDismiss : mPendingDismisses) {
                        // Reset view presentation
                        pendingDismiss.view.setAlpha(1f);
                        pendingDismiss.view.setTranslationX(0);
                        lp = pendingDismiss.view.getLayoutConfig();
                        lp.height = originalHeight;
                        pendingDismiss.view.setLayoutConfig(lp);
                    }

                    // Send a cancel event
//                    long time = Time.getRealActiveTime();
                    mPendingDismisses.clear();
                }
            }

            @Override
            public void onPause(Animator animator) {
            }

            @Override
            public void onResume(Animator animator) {
            }
        });
        animator.setValueUpdateListener((animatorValue, v) -> {
            int height = (int) (originalHeight + v);
            lp.height = Math.min(height, 1);
            dismissView.setLayoutConfig(lp);
        });
        mPendingDismisses.add(new PendingDismissData(dismissPosition, dismissView));
        animator.start();
    }
}
